<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-front-VUE-3-vue-resource - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="vue-resource 除了 vue-resource 之外，还可以使用 axios 的第三方包实现数据的请求 什么是 vue-resource 官网：https://github.com/pagekit/vue-resourc" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-front-VUE-3-vue-resource - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-front-VUE-3-vue-resource" />
<meta property="og:description" content="vue-resource 除了 vue-resource 之外，还可以使用 axios 的第三方包实现数据的请求 什么是 vue-resource 官网：https://github.com/pagekit/vue-resourc" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2018/06/java-front-vue-3-vue-resource/" />
<meta property="article:published_time" content="2018-06-20T10:04:02+08:00" />
<meta property="article:modified_time" content="2018-06-20T10:04:02+08:00" />
<meta itemprop="name" content="Java-front-VUE-3-vue-resource">
<meta itemprop="description" content="vue-resource 除了 vue-resource 之外，还可以使用 axios 的第三方包实现数据的请求 什么是 vue-resource 官网：https://github.com/pagekit/vue-resourc">
<meta itemprop="datePublished" content="2018-06-20T10:04:02&#43;08:00" />
<meta itemprop="dateModified" content="2018-06-20T10:04:02&#43;08:00" />
<meta itemprop="wordCount" content="2619">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-front-VUE-3-vue-resource"/>
<meta name="twitter:description" content="vue-resource 除了 vue-resource 之外，还可以使用 axios 的第三方包实现数据的请求 什么是 vue-resource 官网：https://github.com/pagekit/vue-resourc"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2018/06/java-front-vue-3-vue-resource/"
    >Java-front-VUE-3-vue-resource</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2018/06/java-front-vue-3-vue-resource/" class="article-date">
  <time datetime="2018-06-20 10:04:02 &#43;0800 CST" itemprop="datePublished">2018-06-20</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-front-end/"> Java-front-end </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2018/06/java-front-vue-3-vue-resource/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 2619words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 6minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="vue-resource">vue-resource</h1>
<p>除了 vue-resource 之外，还可以使用 <code>axios</code> 的第三方包实现数据的请求</p>
<h2 id="什么是-vue-resource">什么是 vue-resource</h2>
<p>官网：https://github.com/pagekit/vue-resource</p>
<h2 id="如何使用">如何使用</h2>
<p>vue-resource 依赖于 vue，导包的时候，先导 vue.js，再导 vue-resource.js。顺序不能乱。</p>
<p>导包</p>
<pre><code class="language-html">    &lt;script src=&quot;../js/vue.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;../js/vue-resource.js&quot;&gt;&lt;/script&gt;
</code></pre>
<p>使用</p>
<pre><code class="language-js">// in a Vue instance
this.$http.get('/someUrl', [config]).then(successCallback, errorCallback);
</code></pre>
<p>successCallback 是必须传的，errorCallback 可选</p>
<p>调用方法格式：</p>
<p>List of shortcut methods:</p>
<ul>
<li>get(url, [config])</li>
<li>head(url, [config])</li>
<li>delete(url, [config])</li>
<li>jsonp(url, [config])</li>
<li>post(url, [body], [config])</li>
<li>put(url, [body], [config])</li>
<li>patch(url, [body], [config])</li>
</ul>
<p>参考：https://github.com/pagekit/vue-resource/blob/develop/docs/http.md</p>
<p>入门示例：</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;vue-resource&lt;/title&gt;
    &lt;script src=&quot;../js/vue.js&quot;&gt;&lt;/script&gt;
    &lt;!--注意导包顺序，先 vue.js，再 vue-resource.js--&gt;
    &lt;script src=&quot;../js/vue-resource.js&quot;&gt;&lt;/script&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;../css/bootstrap-3.3.7.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;input type=&quot;button&quot; value=&quot;Get请求&quot; @click=&quot;getInfo&quot;/&gt;
        &lt;input type=&quot;button&quot; value=&quot;Post请求&quot; @click=&quot;postInfo&quot;/&gt;
        &lt;input type=&quot;button&quot; value=&quot;JSONP请求&quot; @click=&quot;jsonpInfo&quot;/&gt;
    &lt;/div&gt;
    &lt;script&gt;
        var vm = new Vue({
            el:'#app',
            data:{},
            methods:{
                getInfo(){
                    this.$http.get('http://127.0.0.1:8080/vue/get').then(function (result) {
                        console.log(result.data)
                    })
                },
                postInfo(){
                    // 第三个参数设置为 emulateJSON: true
                    this.$http.post('http://127.0.0.1:8080/vue/post', {}, {emulateJSON: true}).then(function (result) {
                        console.log(result);
                    });
                },
                jsonpInfo(){
                    this.$http.jsonp('http://127.0.0.1:8080/vue/jsonp').then(result =&gt; {
                        console.log(&quot;result:&quot;+result)
                    })
                }
            }
        })
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>后台代码<code>Controller</code></p>
<pre><code class="language-java">package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(&quot;/vue&quot;)
public class VueTestController {
    @RequestMapping(&quot;/get&quot;)
    @CrossOrigin
    public String testGet() {
        System.out.println(&quot;==========testGet==========&quot;);
        return &quot;index&quot;;
    }

    @RequestMapping(&quot;/post&quot;)
    @ResponseBody
    @CrossOrigin
    public Map&lt;String, String&gt; testPost(){
        Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
        map.put(&quot;a&quot;, &quot;a&quot;);
        map.put(&quot;b&quot;, &quot;b&quot;);
        return map;
    }

    @RequestMapping(&quot;/jsonp&quot;)
    @ResponseBody
    public String testJsonp(HttpServletRequest req) {
        String callback = req.getParameter(&quot;callback&quot;);
        System.out.println(&quot;----callback----:&quot;+callback);
        return callback+&quot;()&quot;;// 返回格式要正确，如 _jsonp1q42uhqydsk({...})，括号里面要是一个 json 对象
    }
}
</code></pre>
<p>后台接口使用<code>@CrossOrigin</code>修饰，避免了“跨域”问题，见附件</p>
<h2 id="使用-vue-resource-改造商品列表">使用 vue-resource 改造商品列表</h2>
<ul>
<li>初始化数据（$http.get/post()）尽量在生命周期的 create 阶段 ——实践过，要在 beforeMount 才行，</li>
<li></li>
</ul>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;品牌列表案例&lt;/title&gt;
    &lt;script src=&quot;../js/vue.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;../js/vue-resource.js&quot;&gt;&lt;/script&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;../css/bootstrap-3.3.7.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;div class=&quot;panel panel-primary&quot;&gt;
            &lt;div class=&quot;panel-heading&quot;&gt;
                &lt;h3 class=&quot;panel-title&quot;&gt;添加品牌&lt;/h3&gt;
            &lt;/div&gt;
            &lt;div class=&quot;panel-body form-inline&quot;&gt;
                &lt;!--&lt;label&gt;ID:&lt;input type=&quot;text&quot; class=&quot;form-control&quot; v-model=&quot;id&quot;&gt;&lt;/label&gt;--&gt;
                &lt;label&gt;Name:&lt;input type=&quot;text&quot; class=&quot;form-control&quot; v-model=&quot;name&quot; @keyup.enter=&quot;add&quot;&gt;&lt;/label&gt;
                &lt;input type=&quot;button&quot; value=&quot;添加&quot; class=&quot;btn btn-primary&quot; @click=&quot;add&quot;/&gt;
                &lt;label&gt;搜索名称关键字：&lt;input type=&quot;text&quot; class=&quot;form-control&quot; v-model=&quot;keywords&quot; v-focus v-color=&quot;'red'&quot;/&gt; &lt;/label&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;table class=&quot;table table-bordered table-hover table-striped&quot;&gt;
            &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;ID&lt;/th&gt;
                &lt;th&gt;Name&lt;/th&gt;
                &lt;th&gt;Ctime&lt;/th&gt;
                &lt;th&gt;Operation&lt;/th&gt;
            &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;
            &lt;tr v-for=&quot;item in search(keywords)&quot; :key=&quot;item.id&quot;&gt;
                &lt;td&gt;{{item.id}}&lt;/td&gt;
                &lt;td&gt;{{item.name}}&lt;/td&gt;
                &lt;td&gt;{{item.ctime | dateFormat('yyyy-mm-dd')}}&lt;/td&gt;
                &lt;td&gt;&lt;a href=&quot;&quot; @click.prevent=&quot;del(item.id)&quot;&gt;删除&lt;/a&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/div&gt;
    &lt;script&gt;
        // 全局-过滤器-时间格式化
        // pattern=&quot;&quot; 默认赋值为&quot;&quot;
        Vue.filter('dateFormat', function (dateStr, pattern=&quot;&quot;) {
            var dt = new Date(dateStr);
            var y = dt.getFullYear();
            var m = (dt.getMonth() + 1).toString().padStart(2,0);
            var d = dt.getDate().toString().padStart(2,0);
            if (pattern.toLowerCase() == &quot;yyyy-mm-dd&quot;) {
                return `${y}-${m}-${d}`;// esc 下面那个键
            } else {
                var h = dt.getHours().toString().padStart(2,0);
                var min = dt.getMinutes().toString().padStart(2,0);
                var s = dt.getSeconds().toString().padStart(2,0);
                return `${y}-${m}-${d} ${h}:${min}:${s}`;
            }
        });
        Vue.directive('focus',{
            // 第一个参数 el：表示被绑定了指令的那个元素，是一个原生 js 对象
            bind:function (el) {

            },
            inserted:function (el) {
                el.focus();
            },
            update:function () {

            }
        });
        Vue.directive('color', {
            bind: function (el,binding) {
                // 内联样式
                // el.style.color = 'red';// 不应该写死，参数应该从页面传来
                el.style.color = binding.value;
            }
        });
        var vm = new Vue({
            el: '#app',
            data: {
                name: '',
                keywords: '',
                list: [
                    {id: 1, name: '奔驰', ctime: new Date()},
                    {id: 2, name: '宝马', ctime: new Date()}
                ]
            },
            // 初始化列表数据
            beforeMount(){
                this.getAllList();
            },
            methods: {
                getAllList(){
                  this.$http.get('http://www.liulongbin.top:3005/api/getprodlist').then(result =&gt; {
                      var result = result.body;
                      if (result.status === 0) {
                          this.list = result.message;
                      } else {
                          alert(&quot;获取数据失败&quot;)
                      }
                  })
                },
                add() {
                    this.$http.post('http://www.liulongbin.top:3005/api/addproduct',
                        {name:this.name},// id 不用传，后台自动生成
                        {emulateJSON: true})
                        .then(result =&gt;{
                            if (result.body.status === 0) {
                                // 添加完成后，查出所有数据回显到表单
                                this.getAllList();
                                this.name = '';
                            }else{
                                alert(&quot;添加失败&quot;);
                            }
                        })
                },
                // 删除
                del(id) {
                    this.$http.get('http://www.liulongbin.top:3005/api/delproduct/' + id).then(result =&gt; {
                        if (result.body.status == 0) {
                            // 刷新页面数据
                            this.getAllList();
                        }else {
                            alert(&quot;删除失败&quot;);
                        }
                    })
                },
                search(keywords) {
                    var newList = [];
                    this.list.forEach(item =&gt; {
                        if (item.name.indexOf(keywords) != -1) {
                            newList.push(item);
                        }
                    });
                    return newList;
                }
            }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="配置数据接口根域名">配置数据接口根域名</h3>
<p>分全局配置和私有配置</p>
<pre><code class="language-js">// 全局配置
Vue.http.options.root = 'http://www.liulongbin.top:3005/';
Vue.http.options.emulateJSON = true;// 全局启用 emulateJSON，这样 $http.post()中就不用写了
</code></pre>
<p>参考：https://github.com/pagekit/vue-resource/blob/develop/docs/config.md</p>
<p>注意：调用的时候，使用相对路径，即，前面不用 <code>/</code>，正确：<code>this.$http.get('api/getprodlist')</code></p>
<h1 id="附件-异常">附件-异常</h1>
<h2 id="no-access-control-allow-origin-header-is-present-on-the-requested-resource">No &lsquo;Access-Control-Allow-Origin&rsquo; header is present on the requested resource</h2>
<p>前端页面请求后台接口时，</p>
<p><img src="https://gitee.com/leafsing/pic/raw/master/img/20200709013844.png" alt=""></p>
<p>解决办法：后端 controller 添加 @CrossOrigin 注解</p>
<pre><code class="language-java">@CrossOrigin
@Controller
@RequestMapping(&quot;/vue&quot;)
public class VueTestController {
    @RequestMapping(&quot;/get&quot;)
    public String testGet() {
        System.out.println(&quot;==========testGet==========&quot;);
        return &quot;index&quot;;
    }
}
</code></pre>
<p>参考：https://blog.csdn.net/qq_37647296/article/details/89401499</p>
<h2 id="cross-origin-read-blocking-corb">Cross-Origin Read Blocking (CORB)</h2>
<p>前端发送 jsonp 请求的时候：</p>
<p><img src="https://gitee.com/leafsing/pic/raw/master/img/20200709013928.png" alt=""></p>
<h1 id="跨域问题">跨域问题</h1>
<h2 id="为什么出现跨域问题">为什么出现“跨域”问题</h2>
<p>因为浏览器有 同源策略，是浏览器搞的鬼。是浏览器根据服务器返回的http头来判断的（参考：https://www.v2ex.com/t/203693）</p>
<p>但 同源策略 是浏览器最基本的安全机制。</p>
<p>所谓同源（即指在同一个域）就是两个页面具有相同的协议（protocol），主机（host）和端口号（port），缺一不可。</p>
<h2 id="如何跨域">如何跨域</h2>
<h3 id="方法一jsonp">方法一：jsonp</h3>
<ul>
<li>总结：在页面中引入一段<code>&lt;script src=&quot;http://localhost:91?callback=f&quot;&gt;</code>代码，其中<code>f</code>是回调函数名称；后台接口返回的数据可能是：<code>f([{},{},...])</code>。
<img src="https://gitee.com/leafsing/pic/raw/master/img/20200709014005.png" alt=""></li>
<li>缺点：只能是 get 请求。——20190925</li>
</ul>
<p>学习资料：https://www.bilibili.com/video/av26167402</p>
<p>示例，效果图：</p>
<p><img src="https://gitee.com/leafsing/pic/raw/master/img/20200709014022.png" alt=""></p>
<p>代码：</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;跨域问题&lt;/title&gt;
    &lt;style type=&quot;text/css&quot;&gt;
        * {
            margin: 0;
            padding: 0;
        }
        ul{
            list-style-type: none;/*列表前面的 * 号去掉*/
        }
        img,input{
            display: block;
            margin: 30px auto;
        }
        #search{
            width: 550px;
            height: 30px;
            margin-bottom: 0;/*下边距*/
        }
        #sugList {
            display: none;
            width: 552px;
            margin: auto;
            border: 1px solid #000;
            border-top: 0;
        }
        #sugList ul li {
            line-height: 30px;
            text-indent: 20px;
        }
        #sugList ul li:hover {
            background: #333;
            color: #fff;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;img src=&quot;../img/baidu.gif&quot; width=&quot;260&quot; alt=&quot;baidu&quot;&gt;
    &lt;input id=&quot;search&quot; type=&quot;text&quot;&gt;
    &lt;div id=&quot;sugList&quot;&gt;
        &lt;ul&gt;
            &lt;!--&lt;li&gt;aa&lt;/li&gt;
            &lt;li&gt;aa&lt;/li&gt;
            &lt;li&gt;aa&lt;/li&gt;
            &lt;li&gt;aa&lt;/li&gt;
            &lt;li&gt;aa&lt;/li&gt;--&gt;
        &lt;/ul&gt;
    &lt;/div&gt;
    &lt;script&gt;
        var search = document.getElementById(&quot;search&quot;);
        var suglist = document.getElementById(&quot;sugList&quot;);
        var ul = document.querySelector(&quot;#sugList ul&quot;);
        search.onkeyup = function search() {
            var sugScript = document.createElement(&quot;script&quot;);
            sugScript.src = &quot;https://www.baidu.com/sugrec?prod=pc&amp;wd=&quot; + this.value + &quot;&amp;cb=getSug&quot;;
            document.body.appendChild(sugScript);
        }
        function getSug(result) {
            var data = result.g;
            if(data != undefined){
                ul.innerHTML = &quot;&quot;;// 删除原来的列表数据
                suglist.style.display = &quot;block&quot;;
                data.forEach(function (el) {
                    var li = document.createElement(&quot;li&quot;);
                    li.innerText = el.q;//  el.q 是取出数据（要调试才知道）
                    ul.appendChild(li);

                    // 开始搜索
                    li.onclick = function () {
                        window.location.href = &quot;https://www.baidu.com/s?wd=&quot; + this.innerText;
                    }
                })
            }else{
                suglist.style.display = &quot;none&quot;;
            }
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>代码在：https://github.com/wolf-lea/heima-vue/blob/master/day02/00.%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98.html#L57</p>
<p>总结——<strong>jsonp的原理</strong>：只有通过 ajax 方式时才会有跨域问题，而通过 href 或 src 请求的 .js/css/img 等文件时，不会存在跨域。</p>
<h3 id="方法二cros">方法二：CROS</h3>
<p>在后台服务器端 response 对象上增加响应头<code>Access-Control-Allow-Origin</code>：</p>
<pre><code>res.header(&quot;Access-Control-Allow-Origin&quot;,&quot;*&quot;);
</code></pre>
<p>在 Spring 4.x 中提供了 <code>@CrossOrigin</code> 注解，可以注解在类或方法上，原理也是添加响应头。</p>
<p>学习资料：https://www.bilibili.com/video/av60490895</p>
<h3 id="方法三nginx-反向代理">方法三：nginx 反向代理</h3>
<p>使用 nginx 反向代理</p>
<h2 id="跨域参考文章">跨域参考文章</h2>
<ul>
<li><a href="https://www.jianshu.com/p/7ce1f8c7a04c">https://www.jianshu.com/p/7ce1f8c7a04c</a></li>
<li><a href="https://blog.csdn.net/weixin_33743880/article/details/91423231">https://blog.csdn.net/weixin_33743880/article/details/91423231</a></li>
<li><a href="https://blog.csdn.net/qq_38128179/article/details/84956552">https://blog.csdn.net/qq_38128179/article/details/84956552</a></li>
<li><a href="https://segmentfault.com/a/1190000015597029?utm_source=tag-newest">https://segmentfault.com/a/1190000015597029?utm_source=tag-newest</a></li>
</ul>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2018/06/java-front-vue-3-vue-resource/" title="Java-front-VUE-3-vue-resource" target="_blank" rel="external">https://rulerLwx.gitee.io/2018/06/java-front-vue-3-vue-resource/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2018/06/java-front-vue-2/" title="Java-front-VUE-2"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2018/06/java-front-vue-4-%E5%8A%A8%E7%94%BB/"
                    title="Java-front-VUE-4-动画"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
